package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.ProductDao;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public int add(ProductModel productModel) {
        String sql = "";
        return JDBC.update(sql);
    }

    @Override
    public int delete(ProductModel productModel) {
        return 0;
    }

    @Override
    public int getCount(ProductModel productModel) {
        String sql = "select count(*) count from (\n" +
                "select p.*,c.name cuisineName from product p\n" +
                "left join cuisine c\n" +
                "on p.cuisine_id=c.id )\n" +
                " temp where  true \n";
        if (!"".equals(productModel.getName())) {
            sql += " and name like '%" + productModel.getName() + "%'";
        }
        return JDBC.getCount(sql);
    }

    @Override
    public List<ProductModel> findAll(ProductModel productModel) {
        String sql = "select * from (\n" +
                "select p.*,c.name cuisineName from product p\n" +
                "left join cuisine c\n" +
                "on p.cuisine_id=c.id )\n" +
                " temp where 1=1\n";
        if (!"".equals(productModel.getName())) {
            sql += " and name like '%" + productModel.getName() + "%'";
        }
        sql += " order by id desc ";
        sql += " limit " + (productModel.getPage() - 1) * productModel.getLimit() + "," + productModel.getLimit();

        List<ProductModel> list = new ArrayList<>();
        ResultSet resultSet = JDBC.query(sql);
        try {
            while (resultSet.next()) {
                ProductModel model = new ProductModel();
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                model.setNormalPrice(resultSet.getBigDecimal("normal_price"));
                model.setPrice(resultSet.getBigDecimal("price"));
                model.setImgHref(resultSet.getString("img_href"));
                model.setIsShow(resultSet.getInt("is_show"));
                model.setCuisineName(resultSet.getString("cuisineName"));
                model.setContent(resultSet.getString("content"));
                model.setCuisineId(resultSet.getInt("cuisine_id"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int update(ProductModel productModel) {
        return 0;
    }

    @Override
    public ProductModel findById(ProductModel productModel) {
        return null;
    }
}
